package cn.tedu.v6;
/**
 *
 */

import java.io.*;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;

public class Server {
    private List<PrintWriter> allOut = new ArrayList<>();
    private List<String> onlineUsers = new ArrayList<>();
    private Map<String, String> userDatabase;
    private static final Integer PORT = 1234;
    private ServerSocket serverSocket;
    private String ip;

    public Server() {
        try {
            serverSocket = new ServerSocket(PORT);
            userDatabase = new HashMap<>();
            userDatabase.put("hanluke", "20040912");
            userDatabase.put("wodi", "20040912");
        } catch (BindException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            while (true) {
                System.out.println("等待客户端的连接");
                Socket socket = serverSocket.accept();
                new Thread(new ClientHandler(socket)).start();
            }
        } catch (IOException e) {
            System.out.println(ip + "客户端链接失效~~");
        } finally {
            if (serverSocket != null && !serverSocket.isClosed()) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    System.out.println("服务器关闭失败~~");
                }
                System.out.println("服务器关闭成功~~");
            }
        }
    }

    public static void main(String[] args) {
        new Server().start();
    }

    private boolean Login(String user, String pass) {
        return userDatabase.containsKey(user) && userDatabase.get(user).equals(pass);
    }

    //同步：broadcastMessage()消息广播
    //参数：String message   转发给客户端  文本
    //增强for  目的：----来一个客户端，给这个客户端加消息

    private class ClientHandler implements Runnable {

        private Socket socket;
        private String ip;
        private PrintWriter pw;
        private BufferedReader br;

        private String username;
        private String password;
        private String message;

        public ClientHandler(Socket s) {
            this.socket = s;
            ip = socket.getInetAddress().getHostAddress();
            System.out.println("客户端：" + ip + "连接上了");
            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
                pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
                //来一个客户端，集合添加可以写出方法
                synchronized (allOut) {
                    //监视集合：只允许一个客户端写出
                    //目的：客户端，写出消息--分发消息
                    allOut.add(pw);
                }

            } catch (UnsupportedEncodingException e) {
                System.out.println();
            } catch (SocketException e) {
                System.out.println();
            } catch (IOException e) {
                System.out.println("客户端断开链接~");
            }
        }
        private synchronized void broadcastMessage(String message) {
            for (PrintWriter pw : allOut) {
                pw.println("消息广播：" + message);
            }
        }
        //理解：broadcastMessage() 功能：获取客户端：转发消息
        private synchronized void broadcastOnlineUsers() {
               synchronized (onlineUsers) {
                   String userList = "在线用户：" + String.join("、", onlineUsers);
                   broadcastMessage("用户名消息"+userList);
               }
        }
//(client = br.readLine()) != null
        private void handlerChat() {
            new Thread(() -> {
                try {
                    String message;
                    while ((message = br.readLine()) != null) {
                        System.out.println(message);
                        broadcastMessage(message);
                        //理解：客户端写出--服务器读入
                        //   转发消息：客户端写出服务器读入的内容
                        broadcastOnlineUsers();
                        System.out.println("服务器请输入：");
                    }
                } catch (IOException e) {
                    System.out.println("服务器端发来的信息断开了");
                }
            }).start();
            Scanner input = new Scanner(System.in);
            while (true) {
                System.out.println("服务器输入");
                String say = input.nextLine();
                pw.println("服务器说：" + say);
                if (say.equalsIgnoreCase("exit")) {
                    System.exit(0);
                }
            }
        }

        @Override
        public void run() {
            try {
                pw.println("请输入用户名:");
                username = br.readLine();
                pw.println("请输入密码:");
                password = br.readLine();
                if (Login(username, password)) {
                    pw.println("登录成功");
                    //3.判断客户端链接成功--加入集合中
                    //3.1【同步块：监视对象--集合】
                    //3.2客户端登录成功--名字加入集合
                    synchronized (onlineUsers) {
                        onlineUsers.add(username);
                        System.out.println(username+"连接成功");
                        broadcastOnlineUsers();
                    }
                    handlerChat();
                } else {
                    pw.println("登录失败，用户名或者密码错误");
                    socket.close();
                }
            } catch (IOException e) {
                System.out.println("服务器读写出现问题！");
            } finally {
                //理解：一个客户端已经转发完毕了，移除当前客户端写出功能
                synchronized (allOut) {
                    //目的：移除，刚刚链接客户端
                    allOut.remove(pw);
                }
                //4.同步块--依次移除用户名不是消息
                synchronized (onlineUsers){
                    onlineUsers.remove(username);
                }
                if (br != null)
                    try {
                        br.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                if (pw != null)
                    pw.close();
                if (socket != null && !socket.isClosed()) {
                    System.out.println(ip + "一个客户端退出服务器链接");
                    try {
                        socket.close();
                    } catch (IOException e) {
                        System.out.println(ip + "一个客户端退出链接异常~~");
                    }
                }
            }
        }
    }
}

